<template>
  <div 
    :class="[
      'bx-dropdown',
      {
        'bx-dropdown--disabled': disabled
      }
    ]"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
  >
    <div 
      ref="triggerRef"
      class="bx-dropdown__trigger"
      @click="handleTriggerClick"
    >
      <slot name="trigger">
        <BxButton>
          {{ triggerText }}
          <BxIcon name="chevron-down" />
        </BxButton>
      </slot>
    </div>

    <teleport to="body">
      <div 
        v-if="visible"
        ref="dropdownRef"
        :class="[
          'bx-dropdown__content',
          'bx-glass',
          `bx-dropdown__content--${placement}`
        ]"
        :style="dropdownStyle"
      >
        <slot></slot>
      </div>
    </teleport>
  </div>
</template>

<script>
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import BxButton from '../basic/BxButton.vue'
import BxIcon from '../basic/BxIcon.vue'

export default {
  name: 'BxDropdown',
  components: {
    BxButton,
    BxIcon
  },
  props: {
    trigger: {
      type: String,
      default: 'hover',
      validator: (value) => ['hover', 'click'].includes(value)
    },
    placement: {
      type: String,
      default: 'bottom-start',
      validator: (value) => [
        'top', 'top-start', 'top-end',
        'bottom', 'bottom-start', 'bottom-end',
        'left', 'left-start', 'left-end',
        'right', 'right-start', 'right-end'
      ].includes(value)
    },
    disabled: {
      type: Boolean,
      default: false
    },
    triggerText: {
      type: String,
      default: 'Dropdown'
    }
  },
  emits: ['visible-change'],
  setup(props, { emit }) {
    const visible = ref(false)
    const triggerRef = ref(null)
    const dropdownRef = ref(null)
    const dropdownStyle = ref({})

    const updatePosition = async () => {
      if (!triggerRef.value || !dropdownRef.value) return

      await nextTick()
      
      const triggerRect = triggerRef.value.getBoundingClientRect()
      const dropdownRect = dropdownRef.value.getBoundingClientRect()
      const viewportWidth = window.innerWidth
      const viewportHeight = window.innerHeight

      let top = 0
      let left = 0

      // 根据placement计算位置
      switch (props.placement) {
        case 'bottom':
        case 'bottom-start':
          top = triggerRect.bottom + 8
          left = props.placement === 'bottom' 
            ? triggerRect.left + (triggerRect.width - dropdownRect.width) / 2
            : triggerRect.left
          break
        case 'bottom-end':
          top = triggerRect.bottom + 8
          left = triggerRect.right - dropdownRect.width
          break
        case 'top':
        case 'top-start':
          top = triggerRect.top - dropdownRect.height - 8
          left = props.placement === 'top'
            ? triggerRect.left + (triggerRect.width - dropdownRect.width) / 2
            : triggerRect.left
          break
        case 'top-end':
          top = triggerRect.top - dropdownRect.height - 8
          left = triggerRect.right - dropdownRect.width
          break
        case 'right':
        case 'right-start':
          top = props.placement === 'right'
            ? triggerRect.top + (triggerRect.height - dropdownRect.height) / 2
            : triggerRect.top
          left = triggerRect.right + 8
          break
        case 'right-end':
          top = triggerRect.bottom - dropdownRect.height
          left = triggerRect.right + 8
          break
        case 'left':
        case 'left-start':
          top = props.placement === 'left'
            ? triggerRect.top + (triggerRect.height - dropdownRect.height) / 2
            : triggerRect.top
          left = triggerRect.left - dropdownRect.width - 8
          break
        case 'left-end':
          top = triggerRect.bottom - dropdownRect.height
          left = triggerRect.left - dropdownRect.width - 8
          break
      }

      // 边界检测
      if (left < 8) left = 8
      if (left + dropdownRect.width > viewportWidth - 8) {
        left = viewportWidth - dropdownRect.width - 8
      }
      if (top < 8) top = 8
      if (top + dropdownRect.height > viewportHeight - 8) {
        top = viewportHeight - dropdownRect.height - 8
      }

      dropdownStyle.value = {
        position: 'fixed',
        top: `${top}px`,
        left: `${left}px`,
        zIndex: 1000
      }
    }

    const show = async () => {
      if (props.disabled) return
      visible.value = true
      emit('visible-change', true)
      await updatePosition()
    }

    const hide = () => {
      visible.value = false
      emit('visible-change', false)
    }

    const handleTriggerClick = () => {
      if (props.trigger === 'click') {
        visible.value ? hide() : show()
      }
    }

    const handleMouseEnter = () => {
      if (props.trigger === 'hover') {
        show()
      }
    }

    const handleMouseLeave = () => {
      if (props.trigger === 'hover') {
        hide()
      }
    }

    const handleClickOutside = (event) => {
      if (!triggerRef.value?.contains(event.target) && 
          !dropdownRef.value?.contains(event.target)) {
        hide()
      }
    }

    onMounted(() => {
      document.addEventListener('click', handleClickOutside)
      window.addEventListener('resize', updatePosition)
      window.addEventListener('scroll', updatePosition)
    })

    onUnmounted(() => {
      document.removeEventListener('click', handleClickOutside)
      window.removeEventListener('resize', updatePosition)
      window.removeEventListener('scroll', updatePosition)
    })

    return {
      visible,
      triggerRef,
      dropdownRef,
      dropdownStyle,
      handleTriggerClick,
      handleMouseEnter,
      handleMouseLeave
    }
  }
}
</script>

<style scoped>
.bx-dropdown {
  display: inline-block;
  position: relative;
}

.bx-dropdown--disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.bx-dropdown__trigger {
  display: inline-block;
}

.bx-dropdown__content {
  min-width: 120px;
  background: var(--bx-glass-bg);
  backdrop-filter: var(--bx-glass-blur-strong);
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-medium);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  padding: var(--bx-spacing-xs);
  font-family: var(--bx-font-family);
  animation: bx-dropdown-fade-in 0.2s ease-out;
}

.bx-dropdown__content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    135deg,
    rgba(255, 255, 255, 0.1) 0%,
    rgba(255, 255, 255, 0.05) 100%
  );
  border-radius: inherit;
  pointer-events: none;
}

@keyframes bx-dropdown-fade-in {
  0% {
    opacity: 0;
    transform: translateY(-8px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bx-dropdown__content {
    min-width: 100px;
    padding: var(--bx-spacing-xs);
  }
}
</style>

